package com.aigou.controller;

import com.aigou.exception.AigouException;
import com.aigou.pojo.PageResult;
import com.aigou.pojo.Result;
import com.aigou.pojo.User;
import com.aigou.service.UserService;
import com.aigou.utils.MD5Util;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    HttpSession session;

    @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    @ResponseBody
    public Result findAll(@RequestParam(value = "page", defaultValue = "1") Integer page
            ,@RequestParam(value = "size", defaultValue = "5")  Integer size, User user) {

        Result result = new Result();
        PageInfo<User> pageInfo = userService.findAll(page, size, user);
        PageResult pr = new PageResult();
        pr.setRows(pageInfo.getTotal());
        pr.setList(pageInfo.getList());
        result.setData(pr);
        return result;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Result add(User user) {
        Result result = new Result();
        userService.add(user);
        return result;
    }

    @RequestMapping(value = "/updatePasswd", method = RequestMethod.POST)
    @ResponseBody
    public Result updatePasswd(String oldPassword, String newPassword) {
        Result result = new Result();
        User user = (User) session.getAttribute("user");
        User dbUser = userService.findOne(user.getId());
        if (!dbUser.getPassword().equals(MD5Util.getMd5(oldPassword))) {
            throw new AigouException("原密码错误");
        }
        user.setPassword(MD5Util.getMd5(newPassword));
        userService.update(user);
        return result;
    }

    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    @ResponseBody
    public Result update(User user) {
        Result result = new Result();
        userService.update(user);
        return result;
    }

    @RequestMapping(value = "/delete/{uid}", method = RequestMethod.DELETE)
    @ResponseBody
    public Result del(@PathVariable("uid") Integer uid) {
        Result result = new Result();
        userService.delete(uid);
        return result;
    }

    @RequestMapping(value = "/findOne/{uid}", method = RequestMethod.GET)
    @ResponseBody
    public Result findOne(@PathVariable("uid") Integer id) {

        // seesion中的id 不等于 id 就报错

        Result result = new Result();
        result.setData(userService.findOne(id));
        return result;
    }

}
